/* 
 *  Copyright (c) 2012 Shirou Maruyama
 * 
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 * 
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above Copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 */

#include <vector>
#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

namespace pacbeep {

using namespace std;

  typedef struct rule_{
    uint32_t left;
    uint32_t right;
  } RULEt;

  void RestoreString(vector<RULEt>& rules, uint32_t code, ostream& os)
  {
    uint32_t left  = rules[code].left;
    uint32_t right = rules[code].right;
    if (code == left && right == kDummy) {
      os.write((char*)&code, 1);
    } else {
      RestoreString(rules, left,  os);
      RestoreString(rules, right, os);
    }
  }

  int slp2txt(istream& is, ostream& os)
  {
    is.seekg(0, ios_base::end);
    uint32_t bytes = is.tellg();
    is.seekg(0, ios_base::beg);
    uint32_t num_rules = bytes / (sizeof(uint32_t)*2) + 256;
    uint32_t start = num_rules - 1;
    vector<RULEt> rules(num_rules);
    for (uint32_t i = 0; i < 256; ++i) {
      rules[i].left  = i;
      rules[i].right = kDummy;
    }
    is.read((char*)&rules[256], sizeof(RULEt) * (num_rules - 256));
    RestoreString(rules, start, os);
    return 1;
  }
  
} // namespace pacbeep
